<template>
  <div>
    <el-page-header @back="goBack" :content="$route.query.id ? '编辑子系统' : '新建子系统'"> </el-page-header>
    <div class="ueba-detail-main">
      <sec-form ref="formData" :ruleForm="ruleForm" :rules="rules" :formData="formData" :optionData="optionData">
        <template v-slot:subsystemList>
          <sec-table
            align="left"
            :tableData="ruleForm.tableData"
            :tableCol="tableCol"
            :header-cell-class-name="inputMust"
            :optionData="tableOptionData"
            :disabledProp="tableDisabledProp"
          ></sec-table>
          <div style="text-align: left" v-if="!$route.query.id">
            <el-button
              style="padding-bottom: 0"
              icon="el-icon-circle-plus-outline"
              size="medium"
              type="text"
              @click="addSubsystemList"
            >
              添加选项
            </el-button>
          </div>
        </template>
      </sec-form>
    </div>
  </div>
</template>

<script>
import { assetsSubsystemDetail } from "api/propertyManage.js";
export default {
  components: {},
  props: {},
  data() {
    return {
      optionData: {},
      rules: {},
      ruleForm: {
        source: "manual",
        remark: "",
        tableData: [{ appID: "" }],
      },
      formData: [
        { title: "基础信息" },
        {
          disabled: true,
          type: "select",
          span: 24,
          label: "资产来源",
          prop: "source",
          option: this.$store.state.dictionary[100100],
        },
        { title: "子系统" },
        { type: "slot", prop: "subsystemList" },
        { title: "其他信息" },
        { type: "textarea", span: 24, label: "备注", prop: "remark" },
        {
          type: "operation",
          style: { "text-align": "center" },
          children: [
            {
              label: "保 存",
              type: "primary",
              click: () => {
                this.isValid = true;
                //if中是验证表单有没有通过，不是提交数据
                if (this.$refs.formData.submitForm()) {
                  //这里是提交数据
                  this.submitSubsystemForm("save");
                }
              },
            },
            {
              label: "保存并发起评估",
              hide: () => {
                return this.$route.query.id;
              },
              type: "primary",
              click: async () => {
                //if中是验证表单有没有通过，不是提交数据
                if (this.$refs.formData.submitForm()) {
                  this.submitSubsystemForm("submit");
                }
              },
            },
          ],
        },
      ],
      tableCol: [
        { type: "text", label: "appID", prop: "assetCode", width: 200 },
        {
          type: "text",
          label: "系统名称",
          prop: "assetName",
          maxlength: 50,
          width: 200,
        },
        {
          type: "text",
          label: "域名",
          prop: "domains",
          placeholder: "多输入，用英文逗号分隔。域名：https://upm.xiaojukeji.com/",
          width: 200,
        },
        {
          type: "text",
          label: "git地址",
          prop: "gits",
          maxlength: 200,
          width: 200,
          placeholder: "多输入，用英文逗号分隔。git地址：git@test.git",
        },
        {
          type: "select",
          label: "权属负责人",
          prop: "leader",
          clearable: true,
          filterable: true,
          remote: true,
          width: 200,
          remoteMethod: async (query) => {
            //select 输入加载下拉框数据
            let res = await this.$store.dispatch("user/getSysUser", { account: query });
            var arr = [];
            res.data.forEach((e) => {
              if (e.name.search("<离职>") == -1) {
                arr.push({
                  label: `${e.account} - ${e.name}`,
                  value: e.account,
                });
              }
            });

            this.tableOptionData.leader = arr;
          },
        },
        {
          type: "select",
          label: "关注人",
          prop: "noticeUsers",
          width: 200,
          multiple: true,
          filterable: true,
          remote: true,
          optionProps: {
            label: (data) => {
              return `${data.account} - ${data.name}`;
            },
            value: "account",
          },
          remoteMethod: async (query) => {
            let res = await this.$store.dispatch("user/getSysUser", { account: query });
            this.tableOptionData.noticeUsers = res.data || [];
          },
        },
        {
          type: "select",
          label: "接入环境",
          prop: "scanDev",
          width: 200,
          optionData: this.$store.state.dictionary["accessDev"],
        },
        {
          type: "operation",
          label: "操作",
          width: 80,
          children: [
            {
              disabled: () => {
                return this.ruleForm.tableData.length === 1;
              },
              icon: "el-icon-remove-outline",
              class: "close-btn select-line-icon",
              click: ({ row, $index }) => {
                this.ruleForm.tableData.splice($index, 1);
              },
            },
          ],
        },
      ],
      tableOptionData: {
        leader: [],
        noticeUsers: [],
      },
      tableDisabledProp: {
        assetCode: false,
      },
    };
  },
  mounted() {
    this.tableDisabledProp.assetCode = this.$route.query.id ? true : false;
    this.initPage();
  },
  methods: {
    inputMust({ columnIndex }) {
      let indexs = [0, 1, 2, 3, 4, 5, 6];
      if (indexs.includes(columnIndex)) {
        return "must";
      }
    },
    initPage() {
      let { id } = this.$route.query;
      //编辑
      if (id) {
        assetsSubsystemDetail({ id }).then((res) => {
          console.log("[ res ] >", res);
          let data = res.data;
          let noticeUserVal = [];
          data.noticeUsers?.map((item) => {
            noticeUserVal.push(item.account);
          });
          this.ruleForm.tableData = [
            {
              id: data.id,
              assetCode: data.assetCode,
              assetName: data.assetName,
              domains: data.domain,
              gits: data.gitList?.join(","),
              leader: data.leader,
              assetType: data.assetType,
              noticeUsers: noticeUserVal,
              scanDev: data.scanDev,
            },
          ];
          this.ruleForm.source = data.source;
          this.ruleForm.remark = data.remark;
        });
      }
    },
    addSubsystemList() {
      this.ruleForm.tableData.push({
        assetCode: "",
        assetName: "",
        domains: "",
        gits: "",
        leader: "",
        noticeUsers: "",
        scanDev: "",
      });
    },
    gitOrDomain() {
      let domainFormat = true;
      let gitFormat = true;
      this.ruleForm.tableData.map((item) => {
        let reg = /^(?:(?:https?:)?\/\/)?(?:[\w-]+\.)*(?:[\w-]+\.[a-z]{2,})(?:\/.*)?$/i;
        const domains = item.domains?.split(",");
        domains?.forEach((domain) => {
          if (!reg.test(domain)) {
            domainFormat = false;
          }
        });
      });
      this.ruleForm.tableData.map((item) => {
        let reg = "^git@.*\\.git$";
        var re = new RegExp(reg);
        const gits = item.gits?.split(",");
        gits?.forEach((git) => {
          if (!re.test(git)) {
            gitFormat = false;
          }
        });
      });
      return { domainFormat, gitFormat };
    },
    // appID是否相同
    isAppIDSame() {
      let obj = {};
      let sign = false;
      this.ruleForm.tableData.forEach((item) => {
        if (obj[item.assetCode]) {
          sign = true;
        } else {
          obj[item.assetCode] = item.assetCode;
        }
      });
      return sign;
    },
    isEmpty() {
      return this.ruleForm.tableData.every((item) => {
        return (
          item.assetCode &&
          item.assetName &&
          item.domains &&
          item.gits?.length > 0 &&
          item.leader &&
          item.noticeUsers &&
          item.scanDev
        );
      });
    },
    async submitSubsystemForm(operate) {
      console.log(this.isEmpty());
      if (!this.isEmpty()) {
        this.message.warning({ message: "子系统表格有必填项未填写" });
        return;
      }
      let regFormat = this.gitOrDomain();
      if (!regFormat.domainFormat) {
        this.message.warning({ message: "域名格式填写不对" });
        return;
      }
      if (!regFormat.gitFormat) {
        this.message.warning({ message: "git地址格式填写不对" });
        return;
      }
      this.ruleForm.tableData.forEach((item) => {
        item.noticeUsers = Array.isArray(item.noticeUsers) ? item.noticeUsers?.join(",") : item.noticeUsers;
      });
      const params = {
        source: this.ruleForm.source,
        remark: this.ruleForm.remark,
        subAssetsSaveDTOs: this.ruleForm.tableData,
        operate,
      };

      const result = this.isAppIDSame();
      if (result.length > 0) {
        this.message.error({ message: "appID重复，请重新输入" });
        return;
      }
      let loading = this.openLoading();
      let res = await this.$store.dispatch("propertyManage/saveSubsystem", params);
      // 失败的条数
      if (res.data.failNums > 0) {
        this.message.error({ message: "appID已存在，请重新输入" });
        loading.close();
        return;
      }
      loading.close();
      let state = this.message.state(res);
      if (!state) return;
      this.goBack();
    },
    goBack() {
      this.$router.push("/property/subsystem/manage");
    },
  },
  computed: {},
  watch: {},
};
</script>
<style lang="scss" scoped>
.check-box {
  margin: 0 0 20px 20px;
}

.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;
  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }
  & .el-input + .el-input {
    margin-left: 4px;
  }
}
.select-item + .select-item {
  margin-top: 4px;
}
.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}
::v-deep .select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  // color: #f56c6c;
}
</style>
